package com.wlyuan.index.remote.facade;

import com.wlyuan.core.domain.valueobj.WaybillId;
import com.wlyuan.core.exception.AssertUtils;
import com.wlyuan.finance.api.IBillService;
import com.wlyuan.finance.api.IWaybillFinanceService;
import com.wlyuan.index.api.dto.waybill.BalanceIndexDTO;
import com.wlyuan.index.api.dto.waybill.BillIndexDTO;
import com.wlyuan.index.domain.source.adapter.BalanceAdapter;
import com.wlyuan.index.domain.source.adapter.BillAdapter;
import com.wlyuan.index.infrastructure.exception.BillNoFound;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yuanjie
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class BillFacade {
    @DubboReference(check = false)
    private IBillService billService;

    @DubboReference(check = false)
    private IWaybillFinanceService financeService;

    public BillIndexDTO getBillById(Long billId) {
        var bill = billService.getBillEventsByBillId(billId);
        AssertUtils.assertNotNull(bill, new BillNoFound(), billId);
        return BillAdapter.translate(bill);
    }

    public List<BillIndexDTO> listBills(Long waybillId) {
        try {
            var bills = billService.getBillEventsByWaybillId(waybillId);
            if (CollectionUtils.isEmpty(bills)) {
                return Collections.emptyList();
            }

            return bills.stream()
                    .map(BillAdapter::translate)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            logger.error("List waybill bills error: {}", waybillId, e);
            return Collections.emptyList();
        }
    }

    public List<BillIndexDTO> listBills(WaybillId waybillId) {
        return this.listBills(waybillId.getId());
    }

    public List<BalanceIndexDTO> listBalances(Long waybillId) {
        var balance = financeService.getEventById(waybillId);
        if (null == balance) {
            logger.debug("Balances for waybill no found: {}", waybillId);
            return Collections.emptyList();
        }
        return Collections.singletonList(BalanceAdapter.translate(balance));
    }

    public List<BalanceIndexDTO> listBalances(WaybillId waybillId) {
        return this.listBalances(waybillId.getId());
    }
}
